/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.servlet;

import cn.easyplatform.lang.Files;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.vos.EnvVo;
import cn.easyplatform.web.WebApps;
import cn.easyplatform.web.contexts.Contexts;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.zkoss.web.servlet.http.Https;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author: <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @Description:
 * @Since: 2.0.0 <br/>
 * @Date: Created in 2019/10/12 14:41
 * @Modified By:
 */
@WebServlet(name = "templateServlet", value = "/template/*")
public class TemplateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        EnvVo env = (EnvVo) req.getSession().getAttribute(Contexts.PLATFORM_APP_ENV);
        if (env == null) {
            resp.sendError(401);
        } else {
            String url = req.getRequestURI().substring(
                    req.getContextPath().length() + 10);
            int pos = url.indexOf(";");
            if (pos > 0)
                url = url.substring(0, pos);
            //String[] data = url.split("/");
            //if (data.length < 3) {
            //resp.sendError(400);
            //} else {
            String path = WebApps.me().getTemplatePath();
            path = path + "/" + env.getProjectId();
            File file = new File(FilenameUtils.normalize(path + "/" + url));
            if (!file.exists() || !file.isFile()) {
                resp.sendError(404);
                return;
            }
            String md5 = file.lastModified() + "";
            if (md5.equals(req.getHeader("if-none-match"))) {
                resp.addHeader("ETag", file.lastModified() + "");
                resp.sendError(304);
            } else {
                byte[] content = FileUtils.readFileToByteArray(file);
                String contentType = Files.getContentType(file);
                resp.setContentType(contentType + ";charset=utf-8");
                //resp.addHeader("Cache-Control", "No-cache");
                resp.addHeader("ETag", file.lastModified() + "");
                resp.addHeader("content-type", contentType);
                OutputStream os = resp.getOutputStream();
                if (content.length > 200) {
                    byte[] bs = Https.gzip(req, resp, null, content);
                    if (bs != null)
                        content = bs; //yes, browser support compress
                }
                resp.setContentLength(content.length);
                os.write(content);
                resp.flushBuffer();
            }
            //}
        }
    }

}
